package cn.tnar.yunpark.huasai;

import io.netty.buffer.ByteBuf;

import java.nio.ByteOrder;

/**
 * Created by tieh on 2016/9/23.
 */
public class HuasaiSensorMessage {
    HuasaiMessageHeader header;
    byte bayCode;
    /**
     * 车位状态，0 - 无车， 1 - 有车
     */
    int status;
    int stopSn; // 批次号，停车车次序号

    /**
     * 电量
     * offset: 26, length:1
     */
    private byte power;

    /**
     * 地磁编号
     * offset: 27, length: 4
     */
    private int magId;

    /**
     * 信号强度(0-7)
     * offset: 31, length: 1
     */
    private byte rssi;

    public HuasaiMessageHeader getHeader() {
        return header;
    }

    public void setHeader(HuasaiMessageHeader header) {
        this.header = header;
    }

    public byte getBayCode() {
        return bayCode;
    }

    public void setBayCode(byte bayCode) {
        this.bayCode = bayCode;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getStopSn() {
        return stopSn;
    }

    public void setStopSn(int stopSn) {
        this.stopSn = stopSn;
    }

    public byte getPower() {
        return power;
    }

    public void setPower(byte power) {
        this.power = power;
    }

    public int getMagId() {
        return magId;
    }

    public void setMagId(int magId) {
        this.magId = magId;
    }

    public byte getRssi() {
        return rssi;
    }

    public void setRssi(byte rssi) {
        this.rssi = rssi;
    }

    public static HuasaiSensorMessage parse(ByteBuf buf) {
        ByteBuf b = buf.order(ByteOrder.LITTLE_ENDIAN);
        HuasaiSensorMessage msg = new HuasaiSensorMessage();
        msg.setHeader(HuasaiMessageHeader.parse(buf));
        msg.setBayCode(b.readByte());
        msg.setStatus(b.readInt());
        msg.setStopSn(b.readUnsignedShort());
        msg.setPower(b.readByte());
        msg.setMagId(b.readInt());
        msg.setRssi(b.readByte());
        b.skipBytes(4);
        return msg;
    }

    /**
     * 车位号(通道号)前面不补零
     * @return
     */
    public String getSensorId() {
        return String.format("%s%d", header.getHostCode(), bayCode);
    }

    public String getPowerShow() {
        int vPower = power * 100;
        if(vPower < 0) {
            vPower = 0;
        } else if(vPower > 700) {
            vPower = 700;
        }
        return Integer.toString(vPower / 7);
    }

    /**
     * 0~7档 => 0% ~ 100%
     * @return
     */
    public String getRssiShow() {
        int scopeRssi = rssi;
        if (rssi < 0) {
            scopeRssi = 0;
        } else if (rssi > 7) {
            scopeRssi = 7;
        }
        return Integer.toString(scopeRssi * 100 / 7);
    }
}
